package com.hualan.sfzy.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hualan.sfzy.constant.CommonConstant;
import com.hualan.sfzy.mapper.ArticleClassifyMapper;
import com.hualan.sfzy.mapper.ArticleMapper;
import com.hualan.sfzy.model.entity.ArticleClassify;
import com.hualan.sfzy.model.vo.ArticleQuery;
import com.hualan.sfzy.service.ArticleClassifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章分类服务实现类
 */
@Service
public class ArticleClassifyServiceImpl implements ArticleClassifyService {
    @Autowired
    private ArticleClassifyMapper articleClassifyMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public int add(ArticleClassify entity) {
        return articleClassifyMapper.insert(entity);
    }

    @Override
    public int edit(ArticleClassify entity) {
        return articleClassifyMapper.update(entity);
    }

    @Override
    public int remove(Integer id) {
        ArticleQuery query=new ArticleQuery();
        query.setClassifyId(id);
        int cont=articleMapper.select(query).size();
        if (cont>0){
            throw  new RuntimeException("该分类下有文章，请先删除文章");
        }
        return articleClassifyMapper.delete(id);
    }

    @Override
    public int removeBatch(Integer[] ids) {
        // 检查每个分类是否有关联文章
        for (Integer id : ids) {
            ArticleQuery query = new ArticleQuery();
            query.setClassifyId(id);
            int count = articleMapper.select(query).size();
            if (count > 0) {
                throw new RuntimeException("ID为" + id + "的分类下有文章，请先删除文章");
            }
        }
        // 所有分类都没有关联文章，执行批量删除
        return articleClassifyMapper.deleteBatch(ids);
    }

    @Override
    public List<ArticleClassify> find() {
        return articleClassifyMapper.select(new ArticleClassify());
    }

    @Override
    public Map<String, Object> findPage(Integer pageNum, Integer pageSize, ArticleClassify entity) {
        PageHelper.startPage(pageNum, pageSize);
        List<ArticleClassify> list = articleClassifyMapper.select(entity);
        PageInfo<ArticleClassify> pageInfo = new PageInfo<>(list);
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put(CommonConstant.PAGE_LIST, list);
        pageMap.put(CommonConstant.PAGE_TOTAL, pageInfo.getPages());
        pageMap.put(CommonConstant.TOTAL, pageInfo.getTotal());
        return pageMap;
    }

    @Override
    public ArticleClassify findById(Integer id) {
        return articleClassifyMapper.selectById(id);
    }
}